﻿using System;
using System.IO;
using System.Net;
using System.Text;
using SS.Common.Map.Model;

namespace SS.Common.Map.MapProvider
{
    public abstract class MapProvider : IMapProvider
    {
        #region Fields

        private const string UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2";
        private const string Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        private readonly CookieContainer _cookies = new CookieContainer();

        private const string languageStr = "en";
        public static string LanguageStr
        {
            get
            {
                return languageStr;
            }
        }

        #endregion

        #region Implementation of IMapConsumer

        public abstract PointLatLng? GetPoint(string rawAddress, out GeoCoderStatusCode status);

        public virtual double GetDistance(PointLatLng point1, PointLatLng point2)
        {
            var lat1 = point1.Lat;
            var lon1 = point1.Lng;
            var lat2 = point2.Lat;
            var lon2 = point2.Lng;

            Func<double, double> deg2rad = deg => deg * (Math.PI / 180);

            const int R = 6371; // Earth's radius (km)
            var dLat = deg2rad(lat2 - lat1);
            var dLon = deg2rad(lon2 - lon1);
            lat1 = deg2rad(lat1);
            lat2 = deg2rad(lat2);

            var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                    Math.Sin(dLon / 2) * Math.Sin(dLon / 2) * Math.Cos(lat1) * Math.Cos(lat2);
            var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));

            return R * c;
        }

        #endregion

        #region Protected methods

        protected string GetContentUsingHttp(string url)
        {
            string ret;
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = Accept;
            request.KeepAlive = true;
            request.Timeout = 0x7530;
            request.ReadWriteTimeout = 0x7530;
            request.Method = "GET";
            request.UserAgent = UserAgent;
            request.CookieContainer = this._cookies;
            request.Referer = url;

            using (var response = request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader read = new StreamReader(responseStream, Encoding.UTF8))
                    {
                        ret = read.ReadToEnd();
                    }
                }
                response.Close();
            }

            return ret;
        }

        #endregion
    }
}
